更改适配器和片段中的文本颜色

时间:2018-07-01 14:11:43

标签: android

美好的一天。我需要通过单击按钮的开关来更改列表视图中的文本颜色。具有自定义适配器和自定义布局的列表视图。在newsitemlist_layout.xml中用适配器正常填充的文本视图可以正常工作,但在片段中给出错误“空对象引用上的Adaptor.setTextColor(int)'”。问题是,如果我在片段中实现了更改文本颜色,则适配器将在片段中初始化,并在主要活动中切换或按钮,但适配器在主要活动中不起作用。因此,现在需要单击主要活动并更改适配器中的文本颜色。有什么办法可以做到这一点。请帮忙。

主要活动。java

 NewsAdaptor adaptor;
   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = (FloatingActionButton)   
findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick ( View view ) {
            Snackbar.make(view, "Replace with your own action", 
Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, 
R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View headerView = navigationView.getHeaderView(0);


aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
       @SuppressLint("ResourceAsColor")
       @Override
       public void onCheckedChanged ( CompoundButton buttonView, 
boolean   isChecked ) {

               adaptor.setTextColor(Color.GREEN);
                adaptor.notifyDataSetChanged();
               } else {


                adaptor.setTextColor(Color.RED);
                adaptor.notifyDataSetChanged();

            }
       }
    });


public boolean onNavigationItemSelected ( MenuItem item ) {
    int id = item.getItemId();


    if (id == R.id.nav_camera) {
        FeagmentA expressMain = new FeagmentA ();
        FragmentManager fragmentManager= getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,expressMain.getTag())
                .commit();
    } else if (id == R.id.nav_gallery) {
        Jungmain expressMain = new Jungmain();
        FragmentManager fragmentManager= getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,expressMain.getTag())
                .commit();
    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;

Fragment.java

public class FragmentA extends Fragment {


public FragmentA() {
    // Required empty public constructor
}
ListView lvRss;
ArrayList<NewsItem> newsItemsList;
NewsAdaptor adapter;
public static FragmentA newInstance(String param1, String param2) {
    FragmentA fragment = new FragmentA();
    Bundle args = new Bundle();

    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {

    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

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

    lvRss = (ListView) view.findViewById(R.id.fragmentalistview);
    newsItemsList = new ArrayList <>();


    new n2().execute();
    return view;
}
private class n2 extends AsyncTask<Integer,Void,Intent> {
    @Override
    protected Intent doInBackground ( Integer... integers ) {
        try {
            Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/pakistan/rss.xml").ignoreHttpErrors(true).get();
            Elements itemElements = document.getElementsByTag("item");
            for (int i = 0; i < itemElements.size(); i++) {
                Element item = itemElements.get(i);
                NewsItem newsItem = new NewsItem();
                newsItem.setImagePath(item.child(5).getElementsByTag("media:thumbnail").first().attr("url"));
                newsItem.setDate(rem1(item.child(4).text()));
                newsItem.setTitle(item.child(0).text());
                newsItem.setLink(item.child(3).text());
                newsItemsList.add(newsItem);
                Collections.sort(newsItemsList, new Comparator<NewsItem>() {
                    @Override
                    public int compare ( NewsItem o1, NewsItem o2 ) {
                        return o1.dateInMilliSec > o2.dateInMilliSec ? -1 :
                                o1.dateInMilliSec < o2.dateInMilliSec ? 1 : 0;
                    }
                });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
       getActivity(). runOnUiThread(new Runnable() {
            @Override
            public void run () {

                adapter = new NewsAdaptor(getContext(), newsItemsList);
                lvRss.setAdapter(adapter);
            }
        });
        return null;
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

}

@Override
public void onDetach() {
    super.onDetach();
}

NewsAdapter.java

 public class NewsAdaptor extends BaseAdapter {
TextView tvtitle;
Context context;
private int color;



public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
    this.context = context;
    this.newsList = newsList;
    this.color = Color.RED;
}

ArrayList <NewsItem> newsList;


@Override
public int getCount () {

    return newsList.size();
}

@Override
public Object getItem ( int position ) {

    return newsList.get(position);
}

@Override
public long getItemId ( int position ) {
    return 0;
}

@SuppressLint("ResourceAsColor")
@Override
public View getView ( int position, View convertView, ViewGroup parent ) {
    if (convertView == null) {
        convertView = View.inflate(context, R.layout.newsitemlist_layout, null);

    }
    NewsItem currentNews = newsList.get(position);
    tvtitle = (TextView) convertView.findViewById(R.id.textView1id);

    tvtitle.setText(currentNews.getTitle());
    tvtitle.setTextColor(color);
    return convertView;
}
public void setTextColor(int color) {
    this.color = color;
}

}

NewsItem.java

 public class NewsItem implements Serializable {

String title;

public String getTitle () {
    return title;
}

public void setTitle ( String title ) {
    this.title = title;
}


@Override
public String toString() {
    return title;
}

NewsItemlist.layout.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp">
<TextView
    android:id="@+id/textView1id"
    android:layout_width="237dp"
    android:layout_height="83dp"
    android:layout_alignEnd="@+id/pubDateid"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/pubDateid"
    android:ellipsize="end"
    android:gravity="right"
    android:text="News TITLE"
    android:textStyle="bold" />

1 个答案:

答案 0 :(得分:0)

尝试一下

在MainActivity Click事件中添加以下代码:

Fragment frag = getSupportFragmentManager().findFragmentById(R.id.containerview); 

    if(frag instanceof FragmentA )
    {
        ((FragmentA ) frag).adapter.setTextColor(Color.RED);
        ((FragmentA ) frag).adapter.notifyDataSetChanged();
    }

已编辑

更改此行

 fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,expressMain.getTag())
            .commit();

收件人

 fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,"TAG_NAME").addToBackStack("TAG_NAME").commit();

然后在活动类中的fragmentmanager中找到片段,如下所示:

Fragment frag = getSupportFragmentManager().findFragmentByTag("TAG_NAME");