2016-10-16 6 views
0

同じ幅と高さの同じ位置に他のボタンのボタンを正確に追加しようとしています。私はこれらのコードのようにそれを行うことができます思っandroid他のボタンにボタンを追加するにはどうすればよいですか?

public class MainActivity extends AppCompatActivity { 

Button b1; 
LinearLayout root; 

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

    root = (LinearLayout)findViewById(R.id.activity_main); 
    b1 = (Button)findViewById(R.id.b1); 

} 

@Override 
public void onWindowFocusChanged(boolean hasFocus) { 
    super.onWindowFocusChanged(hasFocus); 

    ViewGroup.LayoutParams size = new ViewGroup.LayoutParams(b1.getWidth(),b1.getHeight()); 
    int[] locations = new int[2]; 
    b1.getLocationInWindow(locations); 

    Button a = new Button(this); 
    a.setLayoutParams(size); 
    a.setText("new Button"); 
    a.setX(locations[0]); 
    a.setY(locations[1]); 
    root.addView(a); 
} 

}

とXMLを

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/activity_main" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="5dp" 
android:paddingRight="5dp" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:orientation="vertical" 
tools:context="semo.msoft.myapplication.MainActivity"> 
<Button 
android:id="@+id/b1" 
android:layout_width="150dp" 
android:layout_height="150dp" 
android:layout_marginLeft="50dp" 
android:layout_marginTop="50dp"/> 

</LinearLayout> 

しかし、結果は、このようなものだった

resultImage

私はそれが正しいはずだと思ったが、それは間違っているようだ、新しいボタンは少し小さい幅と高さを持っていた。さらに、新しいボタンの位置は全く間違っていました。私はなぜこれについて知っている人が助けてください助けてください

+0

ルートを「」に変更してください。 – Shaishav

+0

@Shaishavありがとうございますが、私も疲れていますが、このように見えます[framLayout result image](0120-17-0553)。 – MWP

答えて

0

次のコードは私のマシンで完全に正常に動作しています。

int[] locations = new int[2]; 
    b1.getLocationInWindow(locations); 

    Button a = new Button(this); 
    a.setLayoutParams(b1.getLayoutParams()); 
    a.setX(locations[0]); 
    a.setY(locations[1]); 
    a.setText("new Button"); 
    frameLayout.addView(a); 

PS:私は基本的にはちょうどあなたがLayoutParamsを設定する方法を変更しますがroot<FrameLayout>に変更する必要があります。 LinearLayoutは重複したビューを扱うことはできません。

+0

あなたの答えをありがとう、私は公にWindowFocusChanged(booleanはFocusを持っています)上のvoid()}これは問題でした!ありがとうございました – MWP

関連する問題