顯示具有 [Android App] 標籤的文章。 顯示所有文章
顯示具有 [Android App] 標籤的文章。 顯示所有文章

2017年4月19日 星期三

[Android] Fragment之間切換

我們在Activity可以用startActivity() / startActivityForResult()來切換Activity之間

但是Fragment之間要怎麼切換呢?

這邊使用TabHost 來分成多頁,在每個Fragment之間要怎麼切換,就是個問題

我們使用FragmentTransaction+FragmentManager來處理這個問題

example:

Fragment galleryFragment = new GalleryFragment();
Bundle args = new Bundle();
args.putString("參數名稱", 參數);
galleryFragment.setArguments(args);//pass argument to target fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();

ft.replace(R.id.container,galleryFragment);
ft.addToBackStack(null);
ft.commit();

GalleryFragment是目的fragment,而這段則是寫在來源fragment

但這邊可能會遇到一個問題(bug)

No View Found For id ...... (illegalStateException)

該怎辦呢?
問題就出在ft.replace(R.id.container,galleryFragment)這行
這個R.id.container必須要在TabHost(Parent)裡面的XML有個FrameLayout

看一下這個TabHost的xml:

<android.support.v4.app.FragmentTabHost    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@android:id/tabhost"    android:layout_width="match_parent"    android:layout_height="match_parent"    >
    <LinearLayout        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="match_parent"        >
        <!-- Tab標籤 -->        <TabWidget            android:id="@android:id/tabs"            android:orientation="horizontal"            android:layout_width="match_parent"            android:layout_height="wrap_content"            />

        <FrameLayout            android:id="@android:id/tabcontent"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:visibility="gone"            />

        <!-- 標籤內容顯示區塊 -->        <FrameLayout            android:id="@+id/container"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_weight="1"            />

    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

有看到@+id/container這個,如果你隨便打content_frame(直接照抄之類的容易出現這樣的錯誤)

就會找不到這個id 因此就在跳轉的時候出現錯誤,所以搞懂了這個問題以後,就可以自己改寫囉!

end

2017年4月12日 星期三

[java] Abstract用法

在寫android app的時候,遇到了一些問題,於是又跑到這邊來記錄一下。


所謂的abstract就是在父類別不實做這個方法,到子類別繼承此父類別時候就可以自由運用(發揮)


ex:


class abstract father
{
    public abstract void test(string str);
    public void main()
   {
           String str = "test";
           test(str);
   }
}

----------------------------------------


class son extends father
{
    public void test(String str)
    {
          //做這邊想要做的事情
          //override (覆寫)
          system.out.print(str);
    }

}


最後在使用的時候可以用

father f = new son();

這樣來宣告

f.main();

則會print 文字test出來

end

2015年1月22日 星期四

[Android] "ClassNotFoundException" / " Binary XML file line # : Error inflating class” / " multiple dex files define"錯誤解決

在寫Android的時候會使用到別人所用的library,

常常會看到ClassNotFound or Binary XML line #數字 Error inflating class

他的意思就是說(如果我沒有會錯意的話)  :他找不到你import的那個library

為什麼呢?

可能性有幾種(我目前知道解決方式也只有兩種,所以就列出兩種)


1) 你沒有正確import Library


請確定這裡面有打勾了,而不是紅色的X (如果沒有正確import就remove掉重新import一次)



通常新建的專案都會有內建android-support-v4.jar 但是你library又有一份,所以就class not found

exception ,因為她不知道要用哪一個(應該是這樣吧?)

這個就簡單一點,把lib資料夾裡面的android-support-v4.jar 刪除就可以了!

當然會造成classnotfoundexception 跟 error inflating class可能原因有很多,只列舉我找到的解決

方式,紀錄一下 End



補充: multiple dex files define 也是有可能有重複的android-support-v4.jar(刪除即可)

2015年1月20日 星期二

[Android] 簡單氣象搜尋 (使用Yahoo Weather api)

氣象主要可以分為兩類:

1)使用地名(自行輸入)搜尋

2)使用座標(GPS)搜尋

這邊實作的部分是(1)

參考資料為:  zh-wang 在 Github上分享的程式碼

不過稍作修改-------下拉式更新天氣 , 跳出視窗式輸入地名

當然介面也有做調整,不過整體架構還是跟著參考資料修改而來的.


----------------------------------------

整個程式就分為3部分

1) 輸入地名(使用AlertDialog技術)

2) 下拉式更新(使用SwipeRefreshLayout技術)

3) 呼叫/解析Yahoo Weather Api 所傳回來的xml(呼叫yahoo Library)


先把MainActivity.class寫出來:

package com.example.weather_practice;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.civetcat.weather.library.WeatherInfo;
import com.civetcat.weather.library.YahooWeather;
import com.civetcat.weather.library.YahooWeather.SEARCH_MODE;
import com.civetcat.weather.library.YahooWeatherInfoListener;

public class MainActivity extends Activity implements YahooWeatherInfoListener {

private ImageView icon_img;
private TextView city_country_txv;
private TextView weather_status1_txv;
private TextView weather_status2_txv;
private TextView temperature_txv;
private AlertDialog dialog;
private static String City_Name;
private SwipeRefreshLayout laySwipe;

private YahooWeather mYahooWeather = YahooWeather.getInstance(5000, 5000, true);


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
        icon_img = (ImageView) findViewById(R.id.icon_img);
        city_country_txv = (TextView) findViewById(R.id.city_country_txv);
        weather_status1_txv = (TextView) findViewById(R.id.weather_status1_txv);
        weather_status2_txv = (TextView) findViewById(R.id.weather_status2_txv);
        temperature_txv = (TextView) findViewById(R.id.temperature_txv);    
       
        search_dialog();

initView();
        //searchByPlaceName("pingtung city");
}

private void search_dialog(){
// -----------取得Layout reference----------
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View view = inflater.inflate(R.layout.input_city, null);      
       
// -----------產生登入視窗--------
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("天氣查詢");
builder.setMessage("輸入查詢天氣城市名稱:(英文)");//"Input Target IP:"
builder.setView(view);
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
EditText edt = (EditText) view.findViewById(R.id.city_edt);
City_Name = edt.getText().toString();
Log.d("show",edt.getText().toString());
searchByPlaceName(edt.getText().toString());
}
});
builder.setNegativeButton("取消", null);
dialog = builder.create();
dialog.show();
}


private void initView(){
laySwipe = (SwipeRefreshLayout) findViewById(R.id.laySwipe);
laySwipe.setOnRefreshListener(onSwipeToRefresh);
laySwipe.setColorSchemeResources(
           android.R.color.holo_red_light,
           android.R.color.holo_blue_light,
           android.R.color.holo_green_light,
           android.R.color.holo_orange_light);
}

private OnRefreshListener onSwipeToRefresh = new OnRefreshListener(){

@Override
public void onRefresh() {
// TODO Auto-generated method stub
laySwipe.setRefreshing(true);
new Handler().postDelayed(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
laySwipe.setRefreshing(false);
searchByPlaceName(City_Name);
Toast.makeText(getApplicationContext(), "Refresh done!", Toast.LENGTH_SHORT).show();
}},5000);
}};

private void searchByPlaceName(String location) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.PLACE_NAME);
Log.d("searchByPlaceName","searchByPlaceName");
mYahooWeather.queryYahooWeatherByPlaceName(getApplicationContext(), location, MainActivity.this);
}

@Override
public void gotWeatherInfo(WeatherInfo weatherInfo) {
// TODO Auto-generated method stub
// 屏東代碼2306213 or TWXX0015
Log.d("got weather info","got weather info");
        if (weatherInfo != null) {
        city_country_txv.setText(City_Name+ ", "+ weatherInfo.getWOEIDCountry());

        weather_status1_txv.setText(weatherInfo.getCurrentConditionDate());
        weather_status2_txv.setText(weatherInfo.getCurrentText());
       
        temperature_txv.setText(weatherInfo.getCurrentTempC()+"℃");

        Log.d("weather info",weatherInfo.getCurrentText());
if (weatherInfo.getCurrentConditionIcon() != null) {
//設定icon

switch(weatherInfo.getCurrentText()){
//不全部列舉,有些不會發生
case "Freezing Drizzle":
break;
case "Drizzle":
break;
case "Freezing Rain":
break;
case "Light Rain":
icon_img.setImageResource(R.drawable.rain_wh);
break;
case "Showers":
break;
case "Blustery":
break;
case "Windy":
break;
case "Cold":
break;
case "Cloudy":
break;
case "Mostly Cloudy":
icon_img.setImageResource(R.drawable.double_cloud_wh);
break;
case "Partly Cloudy":
icon_img.setImageResource(R.drawable.cloud_wh);
break;
case "Clear": //night
break;
case "Sunny":
break;
case "Fair": //day or night
icon_img.setImageResource(R.drawable.night_wh);
break;
case "Hot":
break;
case "Isolated Thunderstorms":
break;
case "Scattered Thunderstorms":
break;
case "Scattered Showers":
break;
case "Thundershowers":
break;
case "Isolated Thundershowers":
break;
case "Haze":
icon_img.setImageResource(R.drawable.haze_wh);
break;
case "Fog":
icon_img.setImageResource(R.drawable.haze_wh);
break;
case "not available":
break;
}
}
        } else {
        }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


********在這邊特別註明一下,yahoo有些天氣狀態還沒更新上去,所以switch case的部分要自行做調整(不過不影響整個程式碼運行)*******


search_dialog()函式就是負責跳出視窗讓使用者可以輸入地名,查詢天氣

initView() 則是初始化下拉式更新的元件

OnRefreshListener() 就監聽 沒別的 onRefresh()裡面就寫你更新時要做的動作,至於handler只是

因為要show toast而已,沒太大用處:)

searchByPlaceName() 這個很重要,他會呼叫到yahoo library 透過

SEARCH_MODE.PLACE_NAME 這方式來搜尋天氣

然後因為我們一開頭有implement YahooWeatherInfoListener 所以他會自己監聽,(裡面有一個函式gotWeatherInfo,就是listener 實作的方法)


詳細的就請大家自己看一下囉,應該不難才對(?)


Activity_main.xml:

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/laySwipe"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#87CEFA"
    android:orientation="vertical"
    tools:context="ah.hathi.simpleweather.WeatherActivity"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/city_country_txv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:gravity="center"
            android:text="城市,國家"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <ImageView
            android:id="@+id/icon_img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/sun_wh" />

        <TextView
            android:id="@+id/weather_status1_txv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="天氣狀態1"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/weather_status2_txv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="天氣狀態2"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" >
        </FrameLayout>

        <TextView
            android:id="@+id/temperature_txv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:gravity="center"
            android:text="溫度"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="@dimen/temperature_text_size" />
    </LinearLayout>

</android.support.v4.widget.SwipeRefreshLayout>


input_city.xml:

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

</EditText>

然後再values/dimens.xml 還有宣告一個

<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="temperature_text_size">30dp</dimen>

</resources>

修改這邊就可以方便修改溫度的字型大小




附上完整檔案,以上 


End


2015年1月14日 星期三

[Android] 基礎Google Map教學

終於把這個很煩人的google map弄出一點樣子

寫在這邊紀錄一下

可能會產生的錯誤會有幾種

1)  INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

2) API Key failed

3) Permission denied



第一種很顯然你刷機(flash ROM)時候法google libary沒有匯入

第二種則是API Key你沒有用你專屬的key ->請到 https://console.developers.google.com/ 申請一

個,申請詳細辦法






切記!!! 你的package name要正確,不正確會無法顯示地圖!!

就把SHA1;package.name輸入在空格中,建立,然後就有API key了

第三種解決方式就是檢查你的AndroidManifest.xml是否有加入適當的permission


-------------------------------------------------------------------------------------------------------------------


以下為三項基礎

1.google play library

首先開啟SDK Manager ->檢查google play service (以下用圖來表示)








有錯誤一定是沒有import正確 / 沒有加入external jar files

然後



這部分需要開啟權限




最後原本的網址載點在這邊

https://github.com/googlemaps/hellomap-android

程式碼跟layout可以上去下載來看看

layout:

<?xml version="1.0" encoding="utf-8"?>
<!--
See this page for more XML attribute options
https://developers.google.com/maps/documentation/android/map#using_xml_attributes
-->
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          map:mapType="normal"/>




MainActivity:

package com.example.hellomap;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public class MainActivity extends FragmentActivity {
    private GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}


就這樣! 

完成圖 End

2015年1月8日 星期四

[Android] 長按切換2個Activity-----intent.setClass錯誤排除-----onGestureListener監聽手勢


為了讓兩個activity能夠順利切換,花了一些時間研究,

當然中間也遇到一些問題,在這邊紀錄一下.


首先切換Activity是使用intent->startActivity()來做切換

觸發則是長按畫面任意地方


首先先看如何監聽手勢(gesture):

OnGestureListener listener = new OnGestureListener(){

@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// TODO Auto-generated method stub
return false;
}

@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
       Intent intent = new Intent();
       intent.setClass(MainActivity.this, switch_target.class);
       startActivity(intent);
       overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
       MainActivity.this.finish();
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
// TODO Auto-generated method stub
return false;
}

@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub

}

@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}};


別忘記要import 所需要的東西

import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;



動畫的部分,首先要在res/anim裡面新增兩個xml檔

第一個檔,檔名隨意設定
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.7"
        android:toYScale="1.0"
        android:fillAfter="false"
        android:startOffset="200"
        android:duration="200" />
    <translate
        android:fromXDelta="50%"
        android:toXDelta="0"
        android:startOffset="200"
        android:duration="200"/>
</set>


第二個檔也是檔名隨意設定


有了動畫xml檔 + 手勢(觸發事件),我們還缺一樣東西,就是切換activity


       Intent intent = new Intent();
       intent.setClass(MainActivity.this, switch_target.class);
       startActivity(intent);
       overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
       MainActivity.this.finish();

切換Activity需要的就是intent,注意這邊

intent.setClass(MainActivity.this, switch_target.class);

是MainActivity.this, switch_target.class兩者是不一樣的,請不要搞錯了(搞錯他就會一直報錯)

 

The method setClass(Context, Class<?>) in the type Intent is not applicable for the arguments...............


這樣的錯誤訊息


另一端切換回來則是:

       Intent intent = new Intent();
       intent.setClass(switch_target.this,MainActivity.class);
       startActivity(intent);
       overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
       switch_target.this.finish();


當然為了避免還是有人看了以後還是出錯,這邊也附上source code 方便大家看

這次的教學就到此囉 End

2014年12月29日 星期一

[Android] No resource found that matches the given name '@style/Theme.AppCompat.Light' / 解決方法

剛開始安裝android / eclipse的時候通常都會遇到這個問題,

相信這個問題困擾許多人已久(包括我)...終於了解+找到解法以後把他寫起來以免下次又忘記!


首先,甚麼叫做IsLibrary?

這個選項打勾就代表說你把該專案當成library(所以不能亂勾,雖然勾了也沒太大影響(?))


Step1:
加入library(File->Import)



選擇sdk-extras-android-support-v7-appcompat資料夾,記得要勾選copy to workspace

Step2:

確認專案->右鍵Properties->anddroid(左側)->Library(isLibrary)是否勾選


Step3:

進到目標Project(就是有錯誤的那個project)

同樣也是properties->android->library->把錯誤的remove掉



add->剛剛新建立的android-support-v7-appcompat->OK (這邊請不要勾選is library)


Step4:

又發現錯誤!!



在builders這邊也有錯所以我們在Builders->Libraries->選擇錯誤的項目->edit->選圖片內的路徑

下面這個也有錯,所以也修正過來

Step5:

完成! 看到style.xml這邊完全沒有錯誤了,project也是沒有驚嘆號出現


就是這樣!幾個步驟做完就可以囉!

如果還是無法記得要去SDK Manager下載新的extras(要按install)

END


2014年12月23日 星期二

[Android] 如何修改Android內Icon

往往製作App的最後一個步驟就是要製作一個Icon,

製作Icon非難事,illustrator即可,甚至icon maker也可以輕意辦到。

但如何把修改好的(製作好的)Icon放進去Eclipse呢?

在專案中找到

1.AndroidManifest.xml

2.點開裡面->Icon->Browse...

3.create new icon..

製作好以後(一直next),選擇你製作好的icon即可。

重新build後,就可以拉!

End.

2014年11月28日 星期五

[Android] 寫入/讀取檔案(內部記憶體)

其實寫入或讀取內部/外部記憶體只差在一個要增加權限(androidmanifest.xml)一個不用而已,

所以如果你是要寫入sd卡,還是可以看一下這篇:)


寫入的部分:

//寫入檔案
private String filename = "MySampleFile.txt";
private String filepath = "MyFileStorage";
File myInternalFile;

.............以上為宣告...................

// 目前時間
Date date = new Date();
// 設定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
// 進行轉換
String dateString = sdf.format(date);

try {
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath,MODE_APPEND);// 不存在就創建,存在就追加
myInternalFile = new File(directory, filename);
FileOutputStream fos = new FileOutputStream(myInternalFile,true);//要加上true才會是append否則預設false
String s = dateString + "," + event+"\n";// +事件
fos.write(s.getBytes());
fos.close();
Log.d("foutstream", "stream");
} catch (IOException e) {
e.printStackTrace();
}

看起來十分簡單,實際運作也十分簡單。

建立一個檔案,這邊記得要用MODE_APPEND(不存在就創建檔案,存在就繼續寫下去),如果用MODE_PRIVATE會蓋掉喔!

然後在FileOutputStream這邊預設是false(append false),因此要改成
FileOutputStream fos = new FileOutputStream(myInternalFile,true);
這樣才能成功複寫。



讀取的部分:

String myData = "";
try {
FileInputStream fis = new FileInputStream(myInternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine + "\n";
}
in.close();
                }catch(Exception e){}


就是用FileInputStream讀取,然後每行每行讀出來,讀到沒有為止,最後記得一樣要關stream!



十分的簡單,但也花了我不少時間,記錄一下。END


2014年11月19日 星期三

[Android] 如何讓TextView可以自動捲軸,當文字超過該範圍時,自動出現scrollbar?

最近寫到一個工具程式可以ping IP,不過因為有時候出現的文字太長了,textview沒辦法完全顯

示,就上網找了一下該如何使用scrollbar呢?


其實很簡單在xml檔的textview裡面增加兩行


        <TextView
            android:id="@+id/Send_txv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:maxLines = "200"
            android:scrollbars = "vertical"          
            android:text=""
            android:textAppearance="?android:attr/textAppearanceSmall" />

第一行的數字可以修改maxLine就是最大顯示多少行,scrollbars則是是要橫幅還是直幅


還沒結束!

在程式碼的部分

Receiver = (TextView) findViewById(R.id.Receive_txv);
Receiver.setMovementMethod(new ScrollingMovementMethod());

並按Ctrl+Shift+O,import需要的東西,就完成囉!


2014年11月17日 星期一

[Android] TextWatcher EditText listener/ EditText的監聽器 & AlertDialog

看到別人都可以輸入完EditText1 就跳到EditText2,到底是如何做到的呢?

如果在主要的xml上面有的EditText 要做到這一部分,相信應該不難,網路上也有。

但如果你是要使用AlertDialog跳出一個視窗,該視窗可以輸入東西(EditText),同時又能輸入完跳

下一個的話,如何做呢?


********************************************
本篇是根據這篇教學: 小黑的android教室 來修改的
********************************************



一開始也是就直接複製過去,沒想到居然出現了nullpointer exception!

想了很久才想到原來是因為我的元件不是在activity_main.xml裡面,而一開始的設定

setContentView又是設定activity_main.xml,這就難怪他抓不到了(R.id.元件名稱)!

再解釋更清楚一點,就是當他跳出這個EditText的時候,卻找不到該元件id號,

NullPointerException的例外狀況馬上跳出來。

所以我們需要使用LayoutInflater.inflate這工具來使他(android)明白我們要用的

R.id.元件名是誰/在哪邊(在哪個xml)。在宣告的時候也要這樣用:

mEdit1 = (EditText) login_view.findViewById(R.id.Edit1);     才行


以下是程式碼


Step1;

在onCreate()這邊要初始化一個TextWatcher模組,讓他可以不停監聽

private void InitTextWatcher() {
// 建立文字監聽
TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// 如果字數達到3,取消自己焦點,下一個EditText取得焦點
if (mEdit1.getText().toString().length() == 3) {
mEdit1.clearFocus();
mEdit2.requestFocus();
}

if (mEdit2.getText().toString().length() == 3) {
mEdit2.clearFocus();
mEdit3.requestFocus();
}

if (mEdit3.getText().toString().length() == 3) {
mEdit3.clearFocus();
mEdit4.requestFocus();
}

// 如果字數達到3,取消自己焦點,隱藏虛擬鍵盤
if (mEdit4.getText().toString().length() == 3) {
mEdit4.clearFocus();
IBinder mIBinder = MainActivity.this.getCurrentFocus()
.getWindowToken();
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mInputMethodManager.hideSoftInputFromWindow(mIBinder,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
};

// 加入文字監聽
mEdit1.addTextChangedListener(mTextWatcher);
mEdit2.addTextChangedListener(mTextWatcher);
mEdit3.addTextChangedListener(mTextWatcher);
mEdit4.addTextChangedListener(mTextWatcher);
}

因為這邊是輸入IP,所以Length設定3。

Step2:

寫一個AlertDialog

public void InitPopup_IP_setting(){
//-----------取得Login Layout reference----------
     LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
     login_view = inflater.inflate(R.layout.ip_setting,null);
   
     //-----------產生登入視窗--------
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
     builder.setTitle("Connect");
     builder.setMessage("Input Target IP:");
     builder.setView(login_view);
     dialog = builder.create();
     dialog.show();
   
 mEdit1 = (EditText) login_view.findViewById(R.id.Edit1);
 mEdit2 = (EditText) login_view.findViewById(R.id.Edit2);
 mEdit3 = (EditText) login_view.findViewById(R.id.Edit3);
 mEdit4 = (EditText) login_view.findViewById(R.id.Edit4);    
     InitTextWatcher();    
}

**這邊有多一個xml檔就是ip_setting**

ip_setting.xml內容:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/Edit1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="fill"
            android:layout_weight="1"
            android:digits="0123456789"
            android:ems="10"
            android:inputType="number"
            android:maxLength="3" >

            <requestFocus />
        </EditText>

        <TextView
            android:id="@+id/TextView05"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="." />

        <EditText
            android:id="@+id/Edit2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:digits="0123456789"
            android:ems="10"
            android:inputType="number"
            android:maxLength="3" />

        <TextView
            android:id="@+id/TextView06"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="." />

        <EditText
            android:id="@+id/Edit3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:digits="0123456789"
            android:ems="10"
            android:inputType="number"
            android:maxLength="3" />

        <TextView
            android:id="@+id/TextView04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="." />

        <EditText
            android:id="@+id/Edit4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:digits="0123456789"
            android:ems="10"
            android:inputType="number"
            android:maxLength="3" />
    </LinearLayout>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="IP_xml_click"
        android:text="Enter" />

</LinearLayout>


好了,就這樣讓AlertDialog+TextWatche完美結合了!

2014年10月28日 星期二

[Android] Navigation Drawer的使用(簡易)

如果有看過Facebook app左側或右側可以拉出來的側邊欄, 那麼你已經看過Navigation Drawer了

不過在實際使用上不是那麼的容易(不然就不用寫教學了), 這邊我也研究了兩次,第一次失敗(覺

得太複雜就先做別的),第二次也就是這次才成功。決定把這個有點難的功能寫下來,當然也不

能說是全部都搞懂,就是把會的寫下來,以免以後忘掉。


這個是完成圖-也就是在手機上左側往右邊拉會出現這樣

的ListView選單。要多少選項可以自行調整(超過螢幕的

長度我就沒有測試了),選項一從編號0開始(所以用switch

case 搭配抓取該item的position就可以應用了)

















已經大概把Navigation Drawer大概介紹完了(詳細介紹可以找網路),先上程式碼:

(程式碼是下載 TonyCube來修改的)

Step1:

private void InitDrawer(){

fragmentManager = getFragmentManager();

layDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
lstDrawer = (ListView) findViewById(R.id.lst_drawer);

layDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

mTitle = mDrawerTitle = getTitle();
drawerToggle = new ActionBarDrawerToggle(
this,
layDrawer,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close) {

@Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
//getActionBar().setTitle(mTitle);
      //這邊可以改string內容,關閉時上方標題會改變,如果沒有要標題就不能用這一行
}

@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//getActionBar().setTitle(R.string.drawer_open);
//這邊可以改string內容,開啟時上方標題會改變,如果沒有要標題就不能用這一行
}
};
drawerToggle.syncState();

layDrawer.setDrawerListener(drawerToggle);
}

首先一定是初始化,因此你需要宣告:

   private ActionBarDrawerToggle drawerToggle;
   private CharSequence mDrawerTitle;
   private CharSequence mTitle;
   private String[] drawer_menu;

以免等等會出現錯誤。

findByViewId的部分就是讓程式知道你要的那個元件是在xml裡面的哪一個,

setDrawerShadows的部分很明顯的就是設定陰影(這邊我沒有修改)

mTitle/Title的部分,如果你前面有設定隱藏title,那麼請把這一行+下面setTitle註解掉,因為會出錯

onDrawerOpen/onDrawerClose就是當側邊欄被拉開時/關閉時的動作,裡面可以自由發揮

setDrawerListener就是設一個監聽器,可以隨時抓取動作


Step2:

private void InitDrawerList(){
drawer_menu = this.getResources().getStringArray(R.array.drawer_menu);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, drawer_menu);

List<HashMap<String,String>> lstData = new ArrayList<HashMap<String,String>>();
//多少個item@String Array => for跑幾次
for (int i = 0; i <drawer_menu.length; i++) {
HashMap<String, String> mapValue = new HashMap<String, String>();
//mapValue.put("icon", Integer.toString(R.drawable.ic_launcher));
              //要圖示的話才需要加這一行
mapValue.put("title", drawer_menu[i]);
lstData.add(mapValue);
}
SimpleAdapter adapter = new SimpleAdapter(this, lstData, R.layout.drawer_list_item2, new String[]{"icon", "title"}, new int[]{R.id.imgIcon, R.id.txtItem});
lstDrawer.setAdapter(adapter);

//側選單點選監聽器
lstDrawer.setOnItemClickListener(new DrawerItemClickListener());
}

這部分是在設定選項,你有多少個選項for就跑多少次(當然在res-value-Strings-StringArray裡面要

先設定好),旁邊圖示我沒有使用,當然要使用的話也是可以就把mapValue那一行重新恢復即

可。一樣設定監聽器,讓使用者點選時可以馬上反應。

Step3:

 private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }
   
private void selectItem(int position) {
        Fragment fragment = null;
        FragmentTransaction fragmentTransaction;
        switch (position) {
case 0:
fragment = new Config();
//layDrawer.closeDrawer(lstDrawer);
info_txv.setVisibility(View.INVISIBLE);
main_txv.setVisibility(View.INVISIBLE);
imageView.setVisibility(View.INVISIBLE);
       fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.Linear_left_drawer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
break;

case 1:
InitPopup_IP_setting();

break;

case 2:
Self_Test();
break;

default:
//還沒製作的選項,fragment 是 null,直接返回
return;
}

        layDrawer.closeDrawer(lstDrawer);
    }

這部分監聽器會監聽使用者點選哪個item,會收到position是哪一個,然後再使用selectItem這個函

式處理,這邊使用switch...case。第一個選項是使用一個fragment去取代目前的fragment,由於

fragmentTransaction.addToBackStack(null)無法回去到原本的fragment,因此這個選項有回不去的

風險,請小心使用。第二個選項這邊是設定AlertDialog(),跟NavigationDrawer不相關,不重要因此

就不贅述,第三個選項亦同,default,或是任何你還沒設定的選項請使用return而不是break,否則就

會看到你的app掛點。最後記得要使用closeDrawer()來關閉NavigationDrawer。



NavigationDrawer大概就是這幾部分,然後如果要新增一個頁面(就是讓你點選一個選項會跳到

另一個頁面)的話,在res-layout這邊新增一個xml檔,在src裡面新增一個java檔*如下圖



這樣就可以連結囉!


以上就是NavigationDraw的小心得。 End


2014年10月17日 星期五

[Android] Sign & Unsign number (0~256) vs (-128~127)

*不一定是完全正確,可參考*

寫android寫到一個難題,解決了以後把他記下來,以免下次又忘記。

這個問題java也會遇到(其實android根本就是用java寫的....),所以java的也可以稍微參考一下

-----------------------------------------------------------------------------------------------------------------------

在android 裡面byte是沒辦法超過127的,所以如果我們要丟128以上的數字出去,就必須要作調整

不然即使強制轉換: (byte)129 這樣 ,仍然無法使用。java的世界裡面只有


0~127(正數)

---------------------------------

128~255(必須用負數表示)


在255的時候為 -1 因此.....128必須用-128表示(128-256 = -128)

也就是說 if( x > 127){
                      x = x-256;
                    }

這樣java才看得懂。

有看到網路上的人用&&FF ,不過那方法我也不太懂,所以就沒用了。

End.
               

2014年10月7日 星期二

[Android] 一些遇到的困難解決方式 跟 經驗談

android 寫到現在終於也快有一個作品出來了,

最常遇到的問題不外乎是import libary是哪一個(整個project掛掉) . R.id無法自動生成 . 明明沒

報錯結果實際run的時候卻出現nullpointer exception....

--------------------------------------------------------------------------------------------------------------------------

這些應該都是android新手常遇到的問題吧?!


  • Library的部分前幾篇有講到,要去properties把某個勾勾去掉




  • R.id無法自動生成 問題可能是出在xml檔有Error (API Level太低或太高,xml碼出錯....)

          解決完畢以後,去Project->clean 即可。同樣你新增一個物件,R.id找不到的時候也是可以

          用clean來處理。


  • 明明沒報錯卻有null pointer exception通常是沒有new,或是找不到id,等等.....
          這邊特別提一下如果你在"非"main thread想要setText或任何改變UI的行為,都會因為找不

          到你要修改的id而產生錯誤,當然即使你有了id number 還是不行,Android只允許在main 

          thread中修改UI部分。

  • 關於Thread / Handler 有些滿不錯的網站:
          Thread & Handler





  • 關於Tab / View這類的
         https://github.com/

         這上面有許多範例程式可以讓你下載回來修改


大概就是這樣,多寫多看囉! over

2014年9月24日 星期三

[Android] ViewPager 遇到在不同xml , 呼叫非setContentView內的R.id.物件 之解決方式

最近在改良Android的APP,先是view flipper,然後現在進階到view pager。

ViewPager可以作出很棒的特效,問題就是在xml方面,如果你要設定物件的話就必須要先

findViewbyId(),這乍聽之下沒甚麼問題,可是假如不是在main.xml檔(主要的xml)的物件呢?

我們使用findViewById()還是可以找到R.id.物件名稱,但只要你一使用的話就會出現錯誤-

java.lang.IllegalState...... NullPointerException....等等。為什麼會出現這樣的錯誤呢?

答案是因為你呼叫的id不在現在的頁面上(Android抓不到他)因此就出現nullpointerException!

在寫的時候也遇到這樣的問題,因此就上網查查看有沒有人也遇到這樣的問題?

發現這篇: 這裡

大意就是說

1.先宣告一個全域變數: private View currentViewPage

2.在 public class MyViewPagerAdapter extends PagerAdapter {} 裡面加入

  @Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
currentViewPage = (View) object;
}

也就是把現在的position的object轉型成view然後放入currentViewPage(第一步驟設定的變數)裡

面。

3.最後   IP_edt = (EditText) currentViewPage.findViewById(R.id.IP_edt01);
      IP_edt.setText("123");

就可以用了喔!(當然IP_edt已經在前面有宣告過了)


希望可以幫助也同樣遇到困難的人!