2017-04-12 1 views
0

나를 복제물로 신고하고 downvotes 롤링을 시작하기 전에, 지금 내가 거의 3 시간 동안이 작업을 할 수있는 모든 것을 다하고 있다는 것을 알아 주시기 바랍니다. 나는 4 가지 방법을 시도했다. Docs와 다양한 포럼 주제에 대해 읽었다. 템플릿/XML을 안드로이드에서 제대로 재사용하는 방법

나는 내가 다음과 같습니다 독립 xml 파일에 정의 Button 있습니다

나는 동적 뷰를 채우는 데 사용하려는
<!--button_template.xml--> 
<Button 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/score_question_btn" 
    android:onClick="viewScore" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="16dp" 
    android:layout_marginLeft="16dp" 
    android:layout_marginRight="16dp" 
    android:padding="24dp" /> 

. '>inflate(R.layout.button_template.xml, rootView, false); 내가 할 수있는 - 버튼이 현재 컨텍스트 루트 뷰의 아이 뷰가 아니기 때문에이 작동하지 않습니다

  • context.findViewById(R.id.button_id); 따라서 null
  • LayoutInflator 반환 지금까지 시도 무엇

    특정 버튼에 다른 텍스트와 배경색을 설정해야하기 때문에이 방법을 사용하십시오. margins을 정의 style resource

  • 를 사용하여 사용자 정의는,하지만 난 Button style
  • Button button = new Button(context) 단순히 내가이 동작하지 않습니다 넣어 설정할 수있는 방법을 찾을 수 없습니다. Button을 만들면 텍스트와 색상을 쉽게 설정할 수 있지만 그 다음은 margins입니다. 반 시간이 Buttonmargin를 괴물이 배치하려고 시도 후

, 나는이 함께했다 :

LinearLayout.LayoutParams params = 
     new LinearLayout.LayoutParams(
       LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
int dpMargin = 16; 
float d = context.getResources().getDisplayMetrics().density; 
int marginInPixels = (int) (dpMargin * d); 
params.setMargins(marginInPixels, marginInPixels, marginInPixels, 0); 

그러나 그렇게된다면이 일관되게 내 프로젝트를 충돌하기 때문에 나는 모르겠다. 한 번 실행되면 충돌이 발생하고 내 프로젝트를 시작할 수 없습니다. 왜냐하면 내 MainActivity class을 찾을 수 없기 때문입니다. 나는 또한 이것을 추적하는 데 1 시간을 보낸다. 내가 고친 유일한 수정 프로그램은 새 프로젝트에 내 src 폴더를 복사하는 것이 었습니다.

그래서 질문 : 올바른 길을 가고 있습니까? 그렇다면 내가 뭘 잘못하고 있니? 그렇지 않다면 - 경험있는 안드로이드 개발자가이 템플레이트 문제에 어떻게 접근할까요? I 버튼 클래스 extend 것이다

+0

"나는 특정 버튼에 다른 텍스트와 배경 색상을 설정해야하기 때문에"- 당신은이 정보를 설정하기 위해'Button' 인스턴스에서 Java 메소드를 호출 할 수 있습니다. 나는 당신이 acheive하려고하는 것을 이해 확실하지 오전 – CommonsWare

+1

... 당신이 "나는 동적보기를 채울를 사용하고 싶습니다."라고합니다. 나는 당신이 버튼 레이아웃 XML을 만들고 다른 레이아웃 내부/일부 선형 레이아웃 등/응용 프로그램의 다른 부분에 해당 버튼을 재사용하려고하는 것 같아요? – ramden

답변

1

.. 여기서

는 예

MyReusableButton.java이다

package com.example.test; 

import android.content.Context; 
import android.graphics.Color; 
import android.util.AttributeSet; 
import android.widget.Button; 
import android.widget.LinearLayout; 

public class MyReusableButton extends Button { 

    //use this constructor for button creation from java code 
    public MyReusableButton(Context context) { 
     super(context); 
     init(); 
    } 

    //this is needed for XML inflation 
    public MyReusableButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    //set button style 
    private void init() { 
     setBackgroundColor(Color.RED); 
     setTextColor(Color.WHITE); 
    } 

    //helper to set margins 
    public void setMargins(int left, int top, int right, int bottom) { 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
     params.setMargins(left, top, right, bottom); 
     this.setLayoutParams(params); 
    } 
} 

MainActivity.java

package com.example.test; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.LinearLayout; 

public class MainActivity extends AppCompatActivity { 

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

     //use this to create a button in code 
     MyReusableButton b = new MyReusableButton(this); 
     b.setText("Hello, World"); 

     //use this to add margins to the button 
     b.setMargins(10, 10, 10, 10); 

     //add the button to the parent linear layout 
     ((LinearLayout) findViewById(R.id.wrapper)).addView(b); 
    } 
} 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/wrapper" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <!-- We can also define a button in XML --> 
    <com.example.test.MyReusableButton 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:text="Test2" 
     /> 
</LinearLayout> 

이 코드의 결과는 프로그래밍 방식으로 생성 된 XML의 버튼과 프로그래밍 된 버튼의 두 버튼입니다. init() 메서드를 사용하면 모든 버튼에서 원하는 스타일을 얻을 수 있습니다.

나중에 코드에 저장할 여백을 설정하는 도우미 메서드가 포함되었습니다.

+0

감사합니다. 나는 그것을 지금 시도 할 것이다. 그 여백은 일반 픽셀이 아닌가? 그렇다면 어떻게 그들을 dp로 만드시겠습니까? – Alex

+0

정말 고마워요. – Alex

+0

문제 없음, dp 로의 변환이 있습니다. 그러나 머리 꼭대기에서 떨어져 있는지, 나는 어딘가에 대답을했다고 확신합니다. – Zach

관련 문제