无法以编程方式在列表视图中设置按钮的可见性

时间:2015-01-23 13:51:29

标签: android listview button android-listview visibility

我正在尝试根据列表视图中的特定条件设置按钮的可见性。

上下文:listview具有响应帖子的参数。它包含响应的标题,描述等以及一个投票按钮。只有作为父帖子所有者的用户应该能够看到该按钮,以便他可以对响应进行投票。

我试图设置按钮可见性的代码的java部分:

adapter= new SimpleAdapter(MainActivity.this, list,
                    R.layout.response_list, columns, mapping);  //response_list is the xml layout file where response parameters are defined.
ListView listView = (ListView) findViewById(R.id.listallresponses); //listallresponses is the id of response_list layout file.

if (!parent.equals(userLoggedin)) { //"parent" is the userid of the parent post. "userLoggedin" is the current user who is viewing the parent post and its responses.
    LayoutInflater li = LayoutInflater.from(this);
    View v = li.inflate(R.layout.response_list, null, false);
    Button upVoteButton = (Button) v
                        .findViewById(R.id.upvoteButton); //upvoteButton is the one whose visibility we are talking about.
    upVoteButton.setVisibility(View.GONE);
}

listView.setAdapter(adapter);

我定义响应参数的response_list.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/responseList"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<!-- Other views are present here-->
<Button
  android:id="@+id/upvoteButton"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="upVoteResponse"
  android:text="VoteUp"/>

问题:upvoteButton始终在响应列表中可见,即使登录的用户不等于父帖子的所有者也是如此。想知道我怎么能让它发挥作用!提前谢谢。

注意:我对Android的熟悉程度只有五个月。我已经搜索了很多,以找出如何使这项工作,但直到现在都无法成功。

1 个答案:

答案 0 :(得分:0)

   LayoutInflater li = LayoutInflater.from(this);
    View v = li.inflate(R.layout.response_list, null, false);
    Button upVoteButton = (Button) v.findViewById(R.id.upvoteButton); 
    upVoteButton.setVisibility(View.GONE);

观点&#34; v&#34; &安培; &#34; upVoteButton&#34;在第2行和第2行中引用3在任何地方都看不到。请注意,您已经夸大了视图&#34; v&#34;和&#34; upVoteButton&#34;已经在内存中膨胀,但在用户界面中没有。

代码中引用的视图和按钮并不是您想要引用的视图和按钮。

你不应该在你的if-block中膨胀任何视图,而是必须使用getView()方法的参数 - 视图和位置来实现你的目标。

相关问题