안드로이드에서 DataBinding
을 사용하는 꽤 깨끗한 접근 방식이 있습니다. 유스 케이스가 어떻게 끝날지에 대한 간단한 예를 살펴 보겠습니다.
첫째, 앱의 build.gradle에서 활성화해야합니다 DataBinding
를 사용 :
android {
dataBinding {
enabled = true
}
}
로그 메시지가 포함됩니다 모델을 생성하는 것, 이것은 또한 깨끗한 방법입니다
두 번째 일 단순히 문자열에 추가하는 대신 메시지를 저장합니다. 내 경우, 나는 그것을 Log
전화 할게 :
public class Log extends BaseObservable{
//This will be the message you wanna print
private String message;
@Bindable
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
//This would automatically update any binded views with this model whenever the message changes
notifyPropertyChanged(BR.message);
}
}
세 번째 것은 당신이 사용하고있는 TextView
가 포함 된 레이아웃 파일을 업데이트하는 것입니다. 기본적으로 레이아웃에 Log
변수를 작성하고 textView
에 메시지를 읽고 텍스트로 표시하도록합니다. 내 예를 들어, activity_main.xml
에서 : 당신이 로그를 표시 싶은 곳
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="log"
type="com.riad.crypto.databinding.Log" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:textSize="18sp"
android:text="@={log.message}" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button_view"
android:gravity="bottom"/>
</LinearLayout>
지금 간단하게하는
Logger
객체를 생성하고
textView
로 바인딩합니다. 내 예를
MainActivity
에서 :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Log logger = new Log();
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLog(logger); //This is where we bind the layout with the object
Button button = (Button) findViewById(R.id.button_view);
logger.setMessage("1st log statement"); //You'll notice that the texview displays this message first
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logger.setMessage("2nd log message"); //After button click, the texview would automatically change text to this. All you did was set the message
}
});
}
그래서 지금 당신은 모든 버튼 클릭에 textView
을 변경할 수 있지만, 당신이 원하는 목적지 당연히 당신은 그것을 할 수 있습니다. 그리고 Log
개체가 다른 클래스에 필요하면 Singleton
또는 뭔가를 만들어이 기능을 향상시킬 수 있지만 데모 용으로 만 사용할 수 있습니다.
희망이 도움이됩니다. Goodluck
[Log 클래스 사용] (https://developer.android.com/reference/android/util/Log.html)? 또는 사용자가이 로그를 보길 원하십니까? 이것이 귀하가 요구하는 것이 아닌 경우 귀하의 질문에보다 구체적으로 기재하십시오. – codeMagic
메시지를 기록하려면 ['Log'] (https://developer.android.com/reference/android/util/Log.html) 클래스를 사용하는 것이 좋습니다. 예를 들어'Log.v (TAG, msg)'를 사용하여 Android 모니터에 자세한 정보를 기록 할 수 있습니다. – ljeabmreosn
@codeMagic 네,하지만 이건 내 TextView에서 인쇄되지 않을 거예요. – Basj