2

它是使用兼容包的小型 Android 2.2 测试应用程序。我正在尝试在列表项选择的另一个活动上更新另一个片段上的文本视图。但问题是,每次第一次单击都会返回空指针异常,并且只有在第二次尝试时,它的文本才会发生变化。我想知道为什么会这样,什么是好的解决方案。

列表活动:-

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);

        }
    }
}

列表片段:-

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);
    }

}

详细活动:-

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();
        }

    }

}

细节片段:-

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>
4

3 回答 3

1

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

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

并在片段 onActivityCreated 通过 getArguments() 获取该值并将其设置在 textview..

编辑发送值选择加载片段

在列表活动中

  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

如果你想每次都替换而不是添加一次并使用添加/加载的片段,每次都使用 setarguments .... 并删除以前的片段并添加新的片段(带参数)但最好添加一次并重用,而不是删除和在每次点击时添加/替换

于 2013-01-23T06:59:49.337 回答
0

你试过用这个吗

TextView view = (TextView) findViewById(R.id.detailView);

而不是这个

 TextView view = (TextView) getView().findViewById(R.id.detailView);
于 2013-01-23T05:07:11.870 回答
0

更新2

只需初始化您TextViewonCreateView()无需DetailFragment使用参数化创建只需添加评论

检查详细信息对象是否为 null 如果 null 像您一样初始化然后调用setTextView()

if(details==null)
    details = new DetailFragment(index);
else
   setTextView(index);

TextView 里面onCreateView()并用了他们的

public class DetailFragment extends Fragment {

    String[] capitals;

    int index;
    private TextView textView;

    public DetailFragment(int index){
        this.index = index;
    }

    @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);
        // Initialize textView
        textView = (TextView) v.findViewById(R.id.detailView);
        setTextView(index); // set value value here for first time
        return v;
    }

    public void setTextView(int index) {
        if(textView!=null)
            textView.setText(capitals[index]); 
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }
}
于 2013-01-23T05:10:46.183 回答