【问题标题】:how to move button in .java如何在.java中移动按钮
【发布时间】:2015-11-19 01:27:03
【问题描述】:

我想向上移动按钮和向下移动文本视图。按钮正在向上移动,但它出现在 textview 上。 Textview 没有下来。

Button b;
TextView t;

public void btnclick(View v){
    b= (Button) v;
    t= (TextView) findViewById(R.id.tv);
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) t
            .getLayoutParams();
    params.addRule(RelativeLayout.BELOW, b.getId());
    b.setLayoutParams(params);

}

【问题讨论】:

  • 你为什么不在 xml 本身做这个?
  • 因为我想在点击后改变它的位置...
  • 试试b.setLayoutParams(params);
  • 尝试改变textview的参数...

标签: android


【解决方案1】:

您似乎正在尝试将规则应用于Button b,而不是尝试将其应用于TextView t。

TextView t = (TextView) findViewById(R.id.tv);

public void btnclick(View v){
    b = (Button) v;
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) t.getLayoutParams();
    params.addRule(RelativeLayout.BELOW, b.getId());
    t.setLayoutParams(params); // Changed this
}

【讨论】:

  • 应用在点击后停止
【解决方案2】:

基本上,RelativeLayout 中的 textview 和 button 尺寸相同。

试试这个代码

活动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mButton;
    private TextView mTextView;

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

        mButton = (Button) findViewById(R.id.btn);
        mButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                mTextView = (TextView) findViewById(R.id.textview);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mTextView.getLayoutParams();
                params.addRule(RelativeLayout.BELOW, v.getId());
                mTextView.setLayoutParams(params);
                break;
        }
    }
}

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test"
        />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"/>

</RelativeLayout>

【讨论】:

  • 在 .xml 中未指定两者的位置时有效。但是,当指定其中任何一个的位置时,它不起作用...
  • 首先,您必须删除规则。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 2011-02-25
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多