android - Textview 在第一次点击时为空,但在第二次点击时更新

标签 android android-fragments android-activity textview

它是使用兼容包的小型 Android 2.2 测试应用程序。我正在尝试在列表项选择的另一个 Activity 中更新另一个 fragment 的 TextView 。但问题是,每次第一次点击都会返回空指针异常,只有在第二次尝试时,它的文本才会改变。我想知道为什么会这样,什么是好的解决方案。

ListActivity:-

public class ListActivity extends FragmentActivity implements
    ListFragment.OnItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
    }

    @Override
    public void onItemSelected(int index) {
        // TODO Auto-generated method stub

        // Check to see if there is a frame in which to embed the
        // detail fragment directly in the containing UI.
        View detailsFrame = findViewById(R.id.detailcontainer);
        if (detailsFrame != null
                && detailsFrame.getVisibility() == View.VISIBLE) {

            DetailFragment detailFragment = (DetailFragment)    getSupportFragmentManager()
                    .findFragmentById(R.id.detailcontainer);

            if (detailFragment == null) {

                detailFragment = new DetailFragment();
            }

            // Execute a transaction, replacing any existing fragment
            // with this one inside the frame.

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.detailcontainer, detailFragment).commit();

            detailFragment.setTextView(index);

        } else {

            // Otherwise we need to launch a new activity to display
            Intent intent = new Intent(this, DetailActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);

        }
    }
}

列表 fragment :-

public class ListFragment extends Fragment {

    private OnItemSelectedListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        String[] countries = new String[] { "India", "Pakistan", "Sri Lanka",
                "China", "Bangladesh", "Nepal", "Afghanistan", "North Korea",
                "South Korea", "Japan" };

        View view = inflater.inflate(R.layout.list_fragment, container, false);

        ListView listView = (ListView) view.findViewById(R.id.listView);

        // Populate list
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this.getActivity(), android.R.layout.simple_list_item_1,
                countries);
        listView.setAdapter(adapter);

        // operation to do when an item is clicked
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(getActivity(), "ListItem Number " + position,
                        Toast.LENGTH_SHORT).show();


                listener.onItemSelected(position);
            }
        });

        return view;
    }

    // Container Activity must implement this interface
    public interface OnItemSelectedListener {
        public void onItemSelected(int index);
    }

    // To ensure that the host activity implements this interface
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet ListFragment.OnItemSelectedListener");
        }
    }

    public void operation(int index) {

        listener.onItemSelected(index);
    }

}

详细 Activity :-

public class DetailActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DetailFragment details;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {

            finish();
            return;
        }

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            details = new DetailFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, details).commit();
        }

        Bundle extras = getIntent().getExtras();
        int index = extras.getInt("index");
        try {
            details = (DetailFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.detailfragment);
            details.setTextView(index);

        } catch (NullPointerException ex) {
            ex.getStackTrace();
        }

    }

}

细节 fragment :-

public class DetailFragment extends Fragment {

    String[] capitals;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (container == null)
            return null;

        capitals = new String[] { "delhi", "karachi", "colombo", "beijing",
                "dhaka", "katmandu", "Afghanistan", "pyongyang", "seoul",
                "tokyo" };

        View v = inflater.inflate(R.layout.detail_fragment, container, false);

        return v;
    }

    public void setTextView(int index) {

        try {
            TextView view = (TextView) getView().findViewById(R.id.detailView);
            view.setText(capitals[index]);

        } catch (NullPointerException ex) {
            ex.getStackTrace();
        }
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }
}

更新:- 我正在添加 detailFragment xml:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="@color/lightblue"
android:orientation="vertical" >

<TextView
    android:id="@+id/detailView"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/detail_frag" />

</RelativeLayout>

最佳答案

不是在 DetailActivity 中执行 details.setTextView(index) ,而是在 DetailFragment 的 onActivityCreated 中设置 TextView 的值,同时传递要在 Detailactivity 中的 fragment setArgument 方法中设置的值...

  DetailsFragment details = new DetailsFragment();
  details.setArguments(getIntent().getExtras());  // pass the value of text view here

然后在 fragment onActivityCreated 中通过 getArguments() 获取该值并将其设置在 textview..

EDIT 发送值 Selected 到加载的 Fragment

在列表 Activity 中

  detailFragment = getFragmentbyTag
  if(detailFragment == null)
      Create Fragment and Add it and Set Arguments here as well
  else
      detailFragment.setTextView(value); // fragment already loaded no need to set arguments

如果你想每次都替换而不是添加一次并使用添加/加载的 fragment ,每次都使用setarguments....并删除以前的 fragment 并添加新 fragment (带参数)但是添加一次并重复使用是首选每次点击删除和添加/替换

关于android - Textview 在第一次点击时为空,但在第二次点击时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14472635/

相关文章:

java - 如何在 android 中处理 "record"和 "replay"触摸事件?

android - 自定义 ListView onitemClick 中的错误

android - Android 布局的 Arc Drawable

java - 如何从 Android 中的 java 代码中删除任何 xml 属性

android - 在 Android 中的 Activity 和 Intent 之间传递整数总是导致零/空

java - 如何更改 SearchView 下方底线的颜色

android - Android 中带有 Sherlock Fragment 的操作栏选项卡的自定义背景

Android如何在 fragment 中显示DatePicker?

java - 基于位置的自动移动静音 Action

android - 使用 FLAG_ACTIVITY_CLEAR_TOP 从非 Activity 类开始 Activity