在创建动态 android 片段时,通过片段管理器我无法根据该片段的视图设置文本

While creating dynamic android fragments, through fragment manager I am unable to setText on view of that fragment

我是 android 的新手,现在已经沉迷其中一段时间​​了。到目前为止,我通过调试检测到的是我的视图为空,这就是它无法为我的 textView 设置值的原因。

有效,非常好:

articleFragment = new ArticleFragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container, articleFragment).commit();
// articleFragment.setText(selectedArticle);

但是当我从最后一行删除评论时,它会显示错误。

以下是class片段:

public class ArticleFragment extends Fragment {
    TextView view;

    /** Called when the activity is first created. */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = (TextView) inflater.inflate(R.layout.article_view, container, false);
        return view;
    }

    public void setText(String text){
        view.setText(text);
    }
}

提前致谢。

更新:

有点风景。在平板电脑视图或横向视图的情况下,此片段的视图不为空。但是如果是移动肖像模式,手表会显示为空。值得一提的是,我还没有为横向和大型布局使用动态片段。 以下是纵向模式 xml 文件: Main.xml

     <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="schemas.android.com/apk/res/android";
      xmlns:tools="schemas.android.com/tools";
      android:orientation="vertical" android:layout_width="match_parent"
      android:layout_height="match_parent" > 

     <FrameLayout xmlns:android="schemas.android.com/apk/res/android";
     android:id="@+id/fragment_container"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

    </LinearLayout> 

ArticleFragment.xml

   <?xml version="1.0" encoding="utf-8"?> 
   <TextView   
   xmlns:android="schemas.android.com/apk/res/android";     
   android:id="@+id/article" android:layout_width="match_parent" 
   android:layout_height="match_parent" android:padding="16dp" 
   android:textSize="18sp" android:text="Article Fragment" /> 

更新 2:

Fragment.java

    package com.example.smd.fragments;

   import android.app.Activity;
   import android.os.Bundle;
   import android.app.Fragment;
   import android.view.LayoutInflater;
   import android.view.ViewGroup;
   import android.view.View;


   public class Fragments extends Activity implements     
       TitleFragment.TitleFragmentListener
 {
private  boolean var;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    var=false;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    if (findViewById(R.id.fragment_container)  != null) {
    TitleFragment titleFragment= new TitleFragment();
        getFragmentManager().beginTransaction().add(R.id.fragment_container, titleFragment).commit();

     var=true;
    }
}

public void onTitleFragmentItemClick(String selectedArticle) {
    ArticleFragment articleFragment = (ArticleFragment) getFragmentManager().findFragmentById(R.id.article);
    if (var == false) {


        if (articleFragment != null)
            articleFragment.setText(selectedArticle);
    }
    else {
        if (findViewById(R.id.fragment_container) != null) {
            articleFragment = ArticleFragment.newInstance("hello world");
            getFragmentManager().beginTransaction().replace(R.id.fragment_container, articleFragment).commit();

        }

    }


}
public void onBackPressed() {
    if (findViewById(R.id.fragment_container) != null) {
        TitleFragment titleFragment= new TitleFragment();
        getFragmentManager().beginTransaction().replace(R.id.fragment_container, titleFragment).commit();
       var=true;
    }

    else
        super.onBackPressed();
}

}

文章Fragment.java

  package com.example.smd.fragments;

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.*;



 public class ArticleFragment extends Fragment
{
TextView view;
private CharSequence text;


public static ArticleFragment newInstance(CharSequence text) {
    Bundle args = new Bundle();
    args.putCharSequence("ArticleFragment", text); // Setup initial text.
    ArticleFragment f = new ArticleFragment();
    f.setArguments(args);
    return f;
}


public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    final Bundle args = getArguments();
    if (icicle != null) {
        // Restore text after config change.
        this.text = icicle.getCharSequence("myText");
    } else if (args != null) {
        // Fragment created for the first time via factory method.
        this.text = args.getCharSequence("myText");
    }
}

/** Called when the activity is first created. */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    view = (TextView) inflater.inflate(R.layout.article_view, container, false);

    onTextChanged();
    return view;
}


public void setText(String text){

    this.text =  text; // Store in field.
    if (view != null) {
        onTextChanged(); // Update view if it's inflated.
    }
}

private void onTextChanged() {
    view.setText(text);
}

}

您的片段膨胀 R.layout.article_view 这很可能不是 TextView,而是 LinearLayout、FrameLayout 等。

因此,您的 R.layout.article_view 应该如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="MissingPrefix"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

完成后,您的 Fragment 应执行以下操作:

  public class ArticleFragment extends Fragment {
    TextView view;

  /** Called when the activity is first created. */
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

    View layout = inflater.inflate(R.layout.article_view, container, false);
    view = (TextView) layout.findViewById(R.id.textView);

    return (layout);
  }


    public void setText(String text) {
      if (view != null) {
        view.setText(text);
      }
    }
 }

这里是你如何以更简单的方式做到这一点:-

您的文章片段

import android.annotation.TargetApi;
imimport android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class ArticleFragment extends Fragment {
    public static final String ARTICLE_NAME = "ArticleName";

    public ArticleFragment() {
    }

    public static ArticleFragment newInstance(String text) {
        ArticleFragment f = new ArticleFragment();
        Bundle bun = new Bundle();
        bun.putString(ARTICLE_NAME, text);
        f.setArguments(bun);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.frag, container, false);

        // Set text directly
        ((TextView) rootView.findViewById(R.id.textView))
                .setText(null != getArguments() ? getArguments().getString(
                        ARTICLE_NAME, "") : "Invalid Article Name");
        return rootView;
    }
}

你的主activityclass

 import android.annotation.TargetApi;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public class CopyOfMainActivity extends FragmentActivity {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, new ArticleFragment("Your article"))
                    .commit();
        }
    }

请注意我有 used.I 的导入正在使用 android.support.V4.app.fragment 来支持旧设备。

您的应用程序正在崩溃,因为在您调用 setText 时片段的视图层次结构尚未扩充 - viewnull。这是一个完整的例子:

ArticleFragment.java

public class ArticleFragment extends Fragment {
    // Fragment stores its own state...
    private CharSequence text;

    // ...and references to its views.
    TextView view;

    /** Your factory method for this fragment. Never use custom costructors with fragments! */
    public static ArticleFragment newInstance(CharSequence text) {
        Bundle args = new Bundle();
        args.putCharSequence("myText", text); // Setup initial text.
        ArticleFragment f = new ArticleFragment();
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        final Bundle args = getArguments();
        if (icicle != null) {
            // Restore text after config change.
            this.text = icicle.getCharSequence("myText"); 
        } else if (args != null) {
            // Fragment created for the first time via factory method.
            this.text = args.getCharSequence("myText");
        } 
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // This is only valid if R.layout.article_view is a TextView!
        view = (TextView) inflater.inflate(R.layout.article_view, container, false);
        onTextChanged(); // Update TextView with saved text if any.
        return view;
    }

    @Override
    public void onDestroyView() {
        this.view = null; // Avoid memory leaks. Clear references to any views.
        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Persist fragment state - "text" - across config changes.
        outState.putCharSequence("myText", this.text); 
        super.onSaveInstanceState(outState);
    }

    public void setText(String text){
        this.text = text; // Store in field.
        if (view != null) {
            onTextChanged(); // Update view if it's inflated.
        }
    }

    private void onTextChanged() {
        view.setText(text);
    }
}

CopyOfMainActivity.java

public class CopyOfMainActivity extends FragmentActivity {

    // Hold reference to fragment so you can call setText later.
    private ArticleFragment articleFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            // Activity is freshly started, create new fragment, attach it.
            articleFragment = ArticleFragment.newInstance("Your article");
            getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, articleFragment)
                .commit();
        } else {
            // After config change the fragment is already loaded. Find it.
            articleFragment = getSupportFragmentManager().findFragmentById(R.id.content);
        }
    }
}

检查 article_view.xml 的所有实例,然后将 TextView 放在 Layout 中,例如 LinearLayout,并给它一个 id,例如 [=16] =]

现在得到 TextView 像:

public class ArticleFragment extends Fragment {
    TextView textView;

    /** Called when the activity is first created. */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.article_view, container, false);
        textView = (TextView) layout.findViewById(R.id.textView);
        return view;
    }

    public void setText(String text){
        textView.setText(text);
    }
}

此外,检查 textView 是否为 null,如果是,则使用 Log.d() 记录事件。